package com.yc.web.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yc.tomcat.core.ConstantInfo;
import com.yc.tomcat.util.StringUtil;

public class HttpServletRequest implements ServletRequest{
private String method;
private Map<String,String> parameter = new HashMap<String, String>();//注意：不考虑复选框
private String url;
private String protocalVersion;//请求的协议版本
private InputStream is = null;
private BufferedReader reader = null;

public HttpServletRequest(InputStream is) {
	this.is = is;
	parse();
}
/**
 * 解析请求
 */
	@Override
	public void parse() {
		try {
			//TODO 处理第一行 请求方式 请求的地址资源 版本协议
			reader = new BufferedReader(new InputStreamReader(is));
			String line = null;
			List<String> headers = new ArrayList<String>();
			
			//读取所有的请求协议
			while((line = reader.readLine()) != null && !"".equals(line)) {
				headers.add(line);
			}
			if(headers.isEmpty()) {
				return;
			}
			//headers.forEach(System.out::println);
			//TODO 处理起始行数据
			parseFirstLine(headers.get(0));
			
			//TODO 解析参数
			parseParameter(headers);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
/**
 * 解析参数
 * @param headers 
 */
	private void parseParameter(List<String> headers) {
	//TODO 解析请求地址中的参数
		String str  = headers.get(0).split(" ")[1];
		if(str.contains("?")) {
			str = str.substring(str.indexOf("?") +1);
			String[] params = str.split("=");
			String[] temp = null;
			for(String param : params) {
				temp = param.split("=");
				if(temp.length == 1) {
					this.parameter.put(temp[0], "");
					continue;
				}
				this.parameter.put(temp[0], temp[1]);
			}
		}
	//TODO 如果是post请求 则要获取请求头协议后面的参数{
		
		if(ConstantInfo.REQUEST_METHOD_POST.equals(this.method)) {
			//TODO 获取到Content-Length
			int len = 0;
			for(String header : headers) {
				if(header.contains("Content-Length")) {
					len = Integer.parseInt(header.substring(header.indexOf(":") +1).trim());
					break;
				}
			}
			if(len <= 0) {
				return;
			}
			
			try {
				//TODO 循坏获取这么长的参数,不处理字节方式
				char[] ch = new char[1024 * 10];
				int count = 0, total = 0;
				StringBuffer sbf = new StringBuffer(1024 * 10);
				while((count = reader.read(ch)) > 0) {
					sbf.append(ch, 0, count);
					total += count;
					if(total >= len) {
						break;
					}
				}
				str = URLDecoder.decode(sbf.toString(), "utf-8");
				String [] params = str.split("&");
				String [] temp = null;
				
				for(String param: params) {
					temp = param.split("=");
					if(temp.length == 1) {
						this.parameter.put(temp[0].trim(), "");
						continue;
					}
					this.parameter.put(temp[0].trim(), temp[1].trim());
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
}
	/**
	 * 处理起始行数据
	 * @param string
	 */
	private void parseFirstLine(String str) {
	if(StringUtil.checkNull(str)) {
		return;
	}
	String[] arrs = str.split(" ");
	this.method = arrs[0];
	this.protocalVersion = arrs[2];
	
	//TODO 检查请求地址中有没有参数
	if(arrs[1].contains("?")) {
		this.url = arrs[1].substring(0, arrs[1].indexOf("?"));
	}else {
		this.url = arrs[1];
	}
}
	@Override
	public String getParameter(String key) {
		return parameter.getOrDefault(key, null);
	}

	@Override
	public String getMethod() {
		return this.method;
	}

	@Override
	public String getUrl() {
		return this.url;
	}
	@Override
	public String getProtocalVersion() {
		return this.protocalVersion;
	}
}
